package com.storage.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.storage.common.core.domain.AjaxResult;
import com.storage.common.core.domain.ServiceResponse;
import com.storage.common.utils.IdentifyCodeUtil;
import com.storage.common.utils.bean.SmsConstant;
import com.storage.system.service.IRedisService;
import com.storage.system.service.ISmsService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 短信服务类
 *
 * @author wb-zh270168
 */
@Service
public class SmsService implements ISmsService {

    private static final Logger logger = LoggerFactory.getLogger(SmsService.class);

    /**
     * 产品名称:云通信短信API产品,开发者无需替换
     */
    static final String product = "Dysmsapi";
    /**
     * 产品域名,开发者无需替换
     */
    static final String domain = "dysmsapi.aliyuncs.com";

    @Value("${aliyun.sms.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.sms.accessKeySecret}")
    private String accessKeySecret;

    @Resource
    private IRedisService redisService;

    /**
     * 发送短信服务
     *
     * @param mobile
     * @return
     */
    @Override
    public AjaxResult sendMessage(String mobile) {
        if (StringUtils.isEmpty(mobile)) {
            return AjaxResult.error(SmsConstant.INVALID_PARAM_MSG);
        }
        String identifyCode;
        //1. 判断是否缓存该账号验证码
        String returnCode = redisService.getValue(mobile);
        if (!StringUtils.isEmpty(returnCode)) {
            identifyCode = returnCode;
        } else {
            identifyCode = IdentifyCodeUtil.getRandom();
        }
        //2.发送短信
        Map<String, String> codeMap = new HashMap<>();
        codeMap.put("code", identifyCode);
        try {
            AjaxResult response = sendSms(mobile, "联合云库", "SMS_172887322", JSON.toJSONString(codeMap), null);
            //短信发送成功后存入redis
            if (response != null && response.getCode() == 0 && StringUtils.isEmpty(returnCode)) {
                redisService.setKey(mobile, identifyCode);
                return response;
            }
            return AjaxResult.error("");
        } catch (Exception e) {
            logger.error("sendMessage method invoke error: {}", e.getMessage());
        }
        return AjaxResult.error("短信发送失败");
    }

    /**
     * 发送短信接口
     *
     * @param phoneNums
     * @param signName      模板签名
     * @param templateCode  模板代码
     * @param templateParam 模板替换参数
     * @param outId         提供给业务方扩展字段
     * @return
     * @throws ClientException
     */
    @Override
    public AjaxResult sendSms(String phoneNums, String signName, String templateCode, String templateParam, String outId) throws ClientException {

        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        //必填:待发送手机号
        request.setPhoneNumbers(phoneNums);
        //必填:短信签名-可在短信控制台中找到
        request.setSignName(signName);
        //必填:短信模板-可在短信控制台中找到
        request.setTemplateCode(templateCode);
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        request.setTemplateParam(templateParam);


        try {
            SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
            if (!sendSmsResponse.getCode().equalsIgnoreCase("OK")) {
                return AjaxResult.error(sendSmsResponse.getMessage());
            }
        } catch (Exception ex) {
            logger.error("阿里云短信发送异常 phone={}; errorMsg={}", phoneNums, ex.getMessage());
        }
        return AjaxResult.success();
    }

    /**
     * 判断验证码是否正确
     *
     * @param mobile
     * @param identifyCode
     * @return
     */
    @Override
    public ServiceResponse<Boolean> checkIsCorrectCode(String mobile, String identifyCode) {
        if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(identifyCode)) {
            return new ServiceResponse<>(false, null, "验证码或者电话号码为空");
        }
        String returnCode = redisService.getValue(mobile);
        if (!StringUtils.isEmpty(returnCode) && returnCode.equals(identifyCode)) {
            redisService.delete(mobile);
            return new ServiceResponse<>(true, null, null);
        }
        return new ServiceResponse<>(false, null, "验证码错误");
    }
}